package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

type DSN struct {
	host, port, username, password, dbname, charset string
	params                                          map[string]string
}

func NewDSN(params map[string]string) (d *DSN) {
	d = new(DSN)
	d.charset = "utf8"
	d.params = make(map[string]string)
	for k, v := range params {
		switch k {
		case "host":
			d.host = v
			break
		case "port":
			d.port = v
			break
		case "username":
			d.username = v
			break
		case "password":
			d.password = v
			break
		case "dbname":
			d.dbname = v
			break
		case "charset":
			d.charset = v
			break
		default:
			d.params[k] = v
			break
		}
	}
	return
}

type model struct {
	conn    *sql.DB
	dsn     *DSN
	err     error
	table   string
	columns []string
	fields  map[string]interface{}
}

func (m *model) connect() (result bool, err error) {
	var p string = fmt.Sprintf("?charset=%s", m.dsn.charset)
	if m.dsn.params != nil {
		for _, key := range m.dsn.params {
			p += fmt.Sprintf("&%s=%s", key, m.dsn.params[key])
		}
	}
	m.conn, m.err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s%s", m.dsn.username, m.dsn.password, m.dsn.host, m.dsn.port, m.dsn.dbname, p))
	result = true
	if m.err != nil {
		//fmt.Println(m.err)
		log.Error(m.err.Error())
		result = false
	}
	return
}

func (m *model) disconnect() (err error) {
	err = m.conn.Close()
	if err != nil {
		log.Error(err.Error())
	}
	return
}

func (m *model) VerifyCC(CCID string, CCPass string) (result bool) {
	_, err := m.connect()
	if err != nil {
		log.Error(err.Error())
		result = false
		return
	}
	defer m.disconnect()

	row := m.conn.QueryRow("select `ID` from `users` where `UserName`=? and `Password`=?", CCID, CCPass)
	var CCid string
	err = row.Scan(&CCid)
	if err != nil {
		//fmt.Println(err)
		log.Error(err.Error())
		result = false
		return
	}
	fmt.Println(CCid)
	result = true
	return
}

func NewModel(dsn *DSN) (m *model) {
	m = new(model)
	m.dsn = dsn
	return m
}
